package com.shjy.driver.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.shjy.driver.amap.LocationUtil;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

/**
 * Created by ld on 2017/6/26.
 */

public class LocationService extends Service {

    public static final String TAG = "LocationService";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

//        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
//        mBuilder.setPriority(Notification.PRIORITY_MIN);// 设置该通知优先级
//        //  mBuilder.setSmallIcon(R.drawable.gpsblue);
//        Notification notification = mBuilder.build();
//        startForeground(1, notification);
        try {
            String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", start service";
            initData(text);
        } catch (Exception e) {
            Log.d("locationsssss", "updateLocation initData " + e.getLocalizedMessage());
        }

        Logger logger = Logger.getLogger(TAG);
        logger.info("logss");
        try {
            String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", go into location";
            initData(text);
            LocationUtil.location(LocationService.this);
        } catch (Exception e) {
            try{
                initData("111error occures in line 263="+e.getMessage()+ " \n");
            }catch (Exception ex){
                ex.printStackTrace();
            }
            Log.d("locationsssss", "updateLocation initData " + e.getLocalizedMessage());
        }
//
//        TimerTask timerTask = new TimerTask() {
//            @Override
//            public void run() {
//                Logger logger = Logger.getLogger(TAG);
//                logger.info("logss");
//                try {
//                    String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", go into location";
//                    initData(text);
//                    LocationUtil.location(LocationService.this);
//                } catch (Exception e) {
//                    try{
//                        initData("111error occures in line 263="+e.getMessage()+ " \n");
//                    }catch (Exception ex){
//                        ex.printStackTrace();
//                    }
//                    Log.d("locationsssss", "updateLocation initData " + e.getLocalizedMessage());
//                }
//            }
//        };
//        Timer timer = new Timer();
//        timer.schedule(timerTask, 0, 5000);
        //return START_REDELIVER_INTENT;
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private static void initData(String text) {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.shjy.driver/files/Download/";
        String fileName = "";
        try {
            fileName = "log-"+formatDate(new Date())+".txt";
        }catch (Exception ex){
            ex.printStackTrace();
        }

        writeTxtToFile(text, filePath, fileName);
    }

    private static  String formatDate(Date date) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath+fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
    }
}
